//
//  UIViewHelper.swift
//  CommonTools
//
//  Created by xianquan on 2024/1/23.
//

import UIKit

public extension CAGradientLayer{
    @discardableResult static func gradient(colors: [UIColor], locations: [NSNumber] = [0, 1], direction: UIView.GradientDirection = .vertical, targetFrame: CGRect = .zero) -> CAGradientLayer{
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = direction == .horizontal ? CGPoint(x: 1.0, y: 0) : CGPoint(x: 0, y: 1.0)
        gradientLayer.colors = colors.map{$0.cgColor}
        gradientLayer.locations = locations
        let gradientFrame =  targetFrame
        gradientLayer.frame = gradientFrame
        return gradientLayer
    }
}

public extension UIView {
    
    enum GradientDirection{
        case horizontal
        case vertical
    }
    
    @discardableResult func addGradient(colors: [UIColor], locations: [NSNumber] = [0, 1], direction: GradientDirection = .vertical, targetFrame: CGRect = .zero) -> CAGradientLayer{
        
        let gradientLayer = CAGradientLayer.gradient(colors: colors, locations: locations, direction: direction, targetFrame: targetFrame == .zero ? bounds : targetFrame)
        layer.insertSublayer(gradientLayer, at: 0)
        return gradientLayer
    }
}

public extension UIView {
    func addShadow(color: UIColor = .black3, opacity: Float = 0.05, radius: CGFloat = 2, offset: CGSize = CGSize(width: 0, height: -2)) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOpacity = opacity
        self.layer.shadowRadius = radius
        self.layer.shadowOffset = offset
    }
}
